<template>
  <div>
    <van-nav-bar title="小鑫头条-登陆" />
    <van-form @submit="onSubmit">
      <van-field
        v-model="user.mobile"
        required
        autocomplete="off"
        name="mobile"
        label="用户名"
        placeholder="请输入11位手机号"
        :rules="[
          { required: true, message: '请填写手机号', pattern: /^1[3-9]\d{9}$/ },
        ]"
      />
      <van-field
        v-model="user.code"
        required
        autocomplete="off"
        type="password"
        name="code"
        label="密码"
        placeholder="请输入6位的密码"
        :rules="[{ required: true, message: '请填写密码', pattern: /^\d{6}$/ }]"
      />
      <div style="margin: 16px">
        <van-button
          round
          block
          type="info"
          native-type="submit"
          :disabled="isLoading"
          :loading="isLoading"
          loading-text="正在登陆ing..."
          >登录</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { loginAPI } from '@/api/index'
import { Notify } from 'vant'
import { setToken } from '../../utils/token'
export default {
  name: 'LoginVue',
  data () {
    return {
      user: {
        mobile: '15972786732', // 手机号
        code: '246810' // 验证码(密码-必须是246810后台规定s的，无论手机号是什么)
      },
      // button按钮状态
      isLoading: false
    }
  },
  methods: {
    async onSubmit () {
      // 状态设置true
      this.isLoading = true
      try {
        const res = await loginAPI(this.user)
        setToken(res.data.data.token)
        localStorage.setItem('refresh_token', res.data.data.refresh_token)
        Notify({ type: 'success', message: '登陆成功' })

        // 成功跳转到首页
        this.$router.replace({
          path: '/layout/home'
        })
      } catch (err) {
        Notify({ type: 'danger', message: '账号或密码错误' })
      }
      this.isLoading = false // 无论是否成功，关闭状态
    }
  }
}
</script>

<style lang="less" scoped>
</style>
